package com.liu.friend.controller;

import com.liu.common.entity.Result;
import com.liu.common.status.CodeEnum;
import com.liu.friend.service.FriendService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2019/8/23 0023.
 */
@RestController
@Slf4j
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private FriendService friendService;



    @Autowired
    private HttpServletRequest request;

    @PutMapping("/add/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid,@PathVariable String type){
//         验证用户是否登录，或者登录情况下，用户是否是前台用户
        Claims claims = (Claims) request.getAttribute("user_claims");
        log.info("request {}",claims);
//        判断用户登录情况，用户没有登录则返回用户登录页面
       if(claims!=null){
//           判断用户登录的角色是不是为user
           if (!claims.get("roles").equals("user")){
//             判断用户是否为添加朋友操作
               if(type.equals("1")){
                   int flag = friendService.addFriend(claims.getId(),friendid);

//                 判断添加朋友是否成功
                   if (flag==1){
                       return new Result(true, CodeEnum.OK.getCode(),"好友添加成功！！！");
                   }
//                判断用
                   return new Result(false, CodeEnum.ERROR.getCode(),"请不要重复添！！！");


               }else if (type.equals("2")){

                   int flag = friendService.addNoFriend(claims.getId(),friendid);

                   return new Result(false, CodeEnum.OK.getCode(),"添加不喜欢的人成功");
               }else {
                   return new Result(false, CodeEnum.ERROR.getCode(),"参数不正确，请核对你提交的参数！！");
               }
           }else {
//               用户登录的角色不是前台用户
               return new Result(false, CodeEnum.ACCESS_ERROR.getCode(),CodeEnum.ACCESS_ERROR.getMessage());
           }
       }else {
//            用户登未登录
           return new Result(false, CodeEnum.ACCESS_ERROR.getCode(),CodeEnum.ACCESS_ERROR.getMessage());
       }

    }


    @DeleteMapping("/{friendid}")
    public Result remove(@PathVariable String friendid){
        Claims claims = (Claims) request.getAttribute("user_claims");
        log.info("request {}",claims);
        if(claims!=null){
           friendService.deleteFriend(claims.getId(),friendid);
           return  new Result(true,CodeEnum.OK.getCode(),"删除好友成功！！！");
        }
        return  new Result(true,CodeEnum.ACCESS_ERROR.getCode(),CodeEnum.ACCESS_ERROR.getMessage());
    }



}
